package com.umanji.generic.entity;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 *
 * @author Daniel Walker <plaxdan@gmail.com>
 */
@MappedSuperclass
@EntityListeners({TimestampEntityListener.class})
public abstract class UUIDEntity<E extends UUIDEntity<?>> extends AbstractEntity<E, Long> { // implements Timestamped {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

	@Column(name = "uuid", updatable = false, nullable = false)
    private UUID uuid;

	@Column(name = "last_update", updatable = false, nullable = false)
    private Date lastUpdate;

    protected UUIDEntity() {
        // Required by JPA
    }

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    @Override
	public UUID getUuid() {
		return uuid;
	}

    @Override
	public void setUuid(UUID uuid) {
		this.uuid = uuid;
	}

    @Override
	public Date getLastUpdate() {
		return lastUpdate;
	}

    @Override
	public void setLastUpdate(Date lastUpdate) {
		this.lastUpdate = lastUpdate;
	}
    
    @Override
	public String getSavedFileName(String RootPath, CommonsMultipartFile fileData, String Sort) {

    	File rootFile = new File(RootPath);
        File sortFile = new File(rootFile, Sort);

    	SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy" + File.separator + "MM", Locale.KOREA );
    	Date today = new Date ( );
    	String datePath = formatter.format ( today );

        File dateFile = new File(sortFile, datePath);
        if (dateFile.isDirectory()) {
        	System.err.println("디렉토리 이미 존재 " + dateFile.toString());
        } else {
            if (!dateFile.mkdirs()) {
            	System.err.println("디렉토리 생성 실패");
            	return "error_creating_directory";
            }
        }

    	String orgFileName = fileData.getOriginalFilename();
    	String fileExt = orgFileName.substring(orgFileName.lastIndexOf(".")+1,orgFileName.length());
    	String newFileName = new StringBuilder().append("umanji").append(today.getTime())
    											.append(UUID.randomUUID()).append(".")
    											.append(fileExt).toString();
    	File destFile = new File(dateFile, newFileName);
    	try {
			fileData.transferTo(destFile);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String destFilePath = destFile.toString();
		return destFilePath.substring(destFilePath.lastIndexOf("upload"), destFilePath.length());
	}

    protected void copy(final UUIDEntity source)
    {
        this.id = source.id;
        super.setVersion( source.getVersion() );
        this.lastUpdate = source.lastUpdate;
    }
    @PrePersist
    protected void initializeId() {
    	this.setUuid(UUID.randomUUID());
    	this.lastUpdate = new Date();
    }

}
